package com.iflytek.aidemo.teacher;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.iflytek.aidemo.R;
import com.iflytek.aidemo.api.ApiService;
import com.iflytek.aidemo.api.ApiServiceImpl;
import com.iflytek.aidemo.model.ClassInfo;
import com.iflytek.aidemo.model.ApiResponse;
import com.iflytek.aidemo.model.Student;
import com.iflytek.aidemo.model.Teacher;
import com.iflytek.aidemo.model.User;
import com.iflytek.aidemo.util.SessionManager;
import android.content.Intent;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 班级管理页面
 * 展示班级内学生的列表，支持添加和删除学生
 */
public class ClassManagementActivity extends AppCompatActivity implements StudentManagementAdapter.OnStudentManagementListener {

    private Spinner spClass;
    private RecyclerView rvStudents;
    private Button btnAddStudent;
    private TextView tvClassInfo;
    private TextView tvEmpty;

    private final List<String> classList = new ArrayList<>();
    private final List<ClassInfo> classInfos = new ArrayList<>();
    private final List<Student> currentStudents = new ArrayList<>();
    private StudentManagementAdapter adapter;
    private Integer selectedClassId = null;
    private String selectedClassName = null;
    private final ApiService api = new ApiServiceImpl();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_class_management);

        // 返回按钮
        View back = findViewById(R.id.btn_back);
        if (back != null) {
            back.setOnClickListener(v -> finish());
        }

        // 初始化视图
        initViews();

        // 设置适配器
        setupAdapters();

        // 加载班级列表
        loadTeacherClasses();

        // 添加学生按钮点击事件
        btnAddStudent.setOnClickListener(v -> showAddStudentDialog());
    }

    private void initViews() {
        spClass = findViewById(R.id.sp_class);
        rvStudents = findViewById(R.id.rv_students);
        btnAddStudent = findViewById(R.id.btn_add_student);
        tvClassInfo = findViewById(R.id.tv_class_info);
        tvEmpty = findViewById(R.id.tv_empty);
    }

    private void setupAdapters() {
        // 班级下拉适配器
        android.widget.ArrayAdapter<String> spinnerAdapter = new android.widget.ArrayAdapter<>(
                this, android.R.layout.simple_spinner_dropdown_item, classList);
        spClass.setAdapter(spinnerAdapter);

        // 班级选择事件
        spClass.setOnItemSelectedListener(new android.widget.AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(android.widget.AdapterView<?> parent, View view, int position, long id) {
                if (position >= 0 && position < classInfos.size()) {
                    selectedClassId = classInfos.get(position).getClassId();
                    selectedClassName = classInfos.get(position).getClassName();
                    tvClassInfo.setText("当前班级: " + selectedClassName);
                    loadClassStudents(selectedClassId);
                }
            }

            @Override
            public void onNothingSelected(android.widget.AdapterView<?> parent) {}
        });

        // 学生列表适配器
        adapter = new StudentManagementAdapter(currentStudents, this);
        rvStudents.setLayoutManager(new LinearLayoutManager(this));
        rvStudents.setAdapter(adapter);
    }

    /**
     * 加载老师的班级列表
     */
    private void loadTeacherClasses() {
        new Thread(() -> {
            try {
                SessionManager sm = new SessionManager(this);
                String userId = sm.getCurrentUser() != null ? sm.getCurrentUser().getUserId() : null;
                ApiResponse<Teacher> response = api.gerTeacherIdByUserId(userId);
                String teacherId = response.getData().getTeacherId();

                ApiResponse<List<ClassInfo>> resp = api.getClassesByTeacher(teacherId == null ? "" : teacherId);
                runOnUiThread(() -> {
                    classList.clear();
                    classInfos.clear();

                    if (resp != null && resp.getCode() == 200 && resp.getData() != null) {
                        classInfos.addAll(resp.getData());
                        for (ClassInfo ci : classInfos) {
                            classList.add(ci.getClassName());
                        }

                        if (!classInfos.isEmpty()) {
                            selectedClassId = classInfos.get(0).getClassId();
                            selectedClassName = classInfos.get(0).getClassName();
                            tvClassInfo.setText("当前班级: " + selectedClassName);
                        }
                    }
                    ((android.widget.ArrayAdapter<?>) spClass.getAdapter()).notifyDataSetChanged();

                    // 如果有选中的班级，加载学生
                    if (selectedClassId != null) {
                        loadClassStudents(selectedClassId);
                    }
                });
            } catch (Exception e) {
                runOnUiThread(() ->
                        Toast.makeText(this, "加载班级失败: " + e.getMessage(), Toast.LENGTH_SHORT).show()
                );
            }
        }).start();
    }

    /**
     * 加载班级学生
     */
    private void loadClassStudents(long classId) {
        new Thread(() -> {
            try {
                ApiResponse<JSONObject> resp = api.getStudentsByClass(classId);
                runOnUiThread(() -> {
                    currentStudents.clear();

                    if (resp != null && resp.getCode() == 200 && resp.getData() != null) {
                        try {
                            JSONArray studentsArray = resp.getData().optJSONArray("students");
                            if (studentsArray != null) {
                                for (int i = 0; i < studentsArray.length(); i++) {
                                    JSONObject studentObj = studentsArray.getJSONObject(i);
                                    Student student = new Student(
                                            studentObj.getLong("studentId"),
                                            studentObj.getString("studentName"),
                                            classId
                                    );
                                    currentStudents.add(student);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(this, "解析学生数据失败", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        String msg = resp != null ? resp.getMessage() : "加载学生失败";
                        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
                    }

                    // 显示空状态或列表
                    if (currentStudents.isEmpty()) {
                        tvEmpty.setVisibility(View.VISIBLE);
                        rvStudents.setVisibility(View.GONE);
                    } else {
                        tvEmpty.setVisibility(View.GONE);
                        rvStudents.setVisibility(View.VISIBLE);
                        adapter.notifyDataSetChanged();
                    }
                });
            } catch (Exception e) {
                runOnUiThread(() ->
                        Toast.makeText(this, "加载学生失败: " + e.getMessage(), Toast.LENGTH_SHORT).show()
                );
            }
        }).start();
    }

    /**
     * 显示添加学生对话框（包含姓名和班级）
     */
    private void showAddStudentDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("添加学生");

        // 加载新的对话框布局
        View view = getLayoutInflater().inflate(R.layout.dialog_add_student_simple, null);
        EditText etName = view.findViewById(R.id.et_student_name);
        EditText etClass = view.findViewById(R.id.et_student_class);
        EditText etPass = view.findViewById(R.id.et_student_pass);

        builder.setView(view);

        // 设置确定按钮
        builder.setPositiveButton("添加", (dialog, which) -> {
            String name = etName.getText().toString().trim();
            String classNameOrId = etClass.getText().toString().trim();
            String password = etPass.getText().toString().trim();

            if (name.isEmpty()) {
                Toast.makeText(this, "请输入学生姓名", Toast.LENGTH_SHORT).show();
                return;
            }

            if (classNameOrId.isEmpty()) {
                Toast.makeText(this, "请输入班级信息", Toast.LENGTH_SHORT).show();
                return;
            }

            // 创建学生并加入班级
            createStudentAndAddToClass(name, classNameOrId, password);
        });

        builder.setNegativeButton("取消", null);
        builder.show();
    }

    /**
     * 创建学生并直接加入指定班级
     */
    private void createStudentAndAddToClass(String name, String classNameOrId, String password) {
        new Thread(() -> {
            try {
                // 1. 创建学生

                ApiResponse<User> createResp = api.createStudent(name, password);

                if (createResp != null && createResp.getCode() == 200 && createResp.getData() != null) {
                    // 2. 获取班级ID（根据实际需求转换：如果输入的是名称，需要先查询ID）
                    Long classId = Long.parseLong(classNameOrId);

                    // 3. 将学生添加到班级
                    ApiResponse<Boolean> addResp = api.addStudentToClass(classId, Long.parseLong(createResp.getData().getUserId()));

                    runOnUiThread(() -> {
                        if (addResp != null && addResp.getCode() == 200 && addResp.getData()) {
                            Toast.makeText(this, "学生创建并加入班级成功", Toast.LENGTH_SHORT).show();
                            loadClassStudents(classId); // 刷新对应班级的学生列表
                        } else {
                            String msg = addResp != null ? addResp.getMessage() : "添加到班级失败";
                            Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
                        }
                    });
                } else {
                    String msg = createResp != null ? createResp.getMessage() : "创建学生失败";
                    runOnUiThread(() -> Toast.makeText(this, msg, Toast.LENGTH_SHORT).show());
                }
            } catch (Exception e) {
                runOnUiThread(() ->
                        Toast.makeText(this, "操作失败: " + e.getMessage(), Toast.LENGTH_SHORT).show()
                );
            }
        }).start();
    }

    /**
     * 解析班级ID（根据实际业务逻辑实现）
     */
//    private Long parseClassId(String classNameOrId) {
//        // 这里根据实际需求实现：
//        // 1. 如果输入的是数字ID，直接转换
//        // 2. 如果输入的是名称，调用API查询对应的ID
//        try {
//            return Long.parseLong(classNameOrId);
//        } catch (NumberFormatException e) {
//            // 名称转ID的逻辑（示例）
//            for (ClassInfo info : classInfos) {
//                if (info.getClassName().equals(classNameOrId)) {
//                    return info.getClassId().longValue();
//                }
//            }
//            return null;
//        }
//    }

    /**
     * 删除学生
     */
    private void deleteStudent(long studentId) {
        if (selectedClassId == null) return;

        new Thread(() -> {
            try {
                ApiResponse<Boolean> resp = api.removeStudentFromClass(
                        selectedClassId.longValue(),
                        studentId
                );

                runOnUiThread(() -> {
                    if (resp != null && resp.getCode() == 200 && resp.getData()) {
                        Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
                        loadClassStudents(selectedClassId); // 刷新列表
                    } else {
                        String msg = resp != null ? resp.getMessage() : "删除失败";
                        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
                    }
                });
            } catch (Exception e) {
                runOnUiThread(() ->
                        Toast.makeText(this, "删除失败: " + e.getMessage(), Toast.LENGTH_SHORT).show()
                );
            }
        }).start();
    }

    @Override
    public void onDeleteClick(Student student) {
        new AlertDialog.Builder(this)
                .setTitle("确认删除")
                .setMessage("确定要将 " + student.getName() + " 从班级中移除吗？")
                .setPositiveButton("确定", (dialog, which) -> deleteStudent(student.getId()))
                .setNegativeButton("取消", null)
                .show();
    }

    @Override
    public void onItemClick(Student student) {
        // 可以跳转到学生详情页（如果需要）
        Toast.makeText(this, "选中: " + student.getName(), Toast.LENGTH_SHORT).show();
    }
}
